import React, { useState } from 'react';
import * as Doms from "@/components/APreviewCom";
import { Tabs, Spin, Empty, Tooltip, Pagination, Modal, Button } from 'antd';
import { history } from "umi";
import styles from "./index.less";
import { ArrowLeftOutlined, UploadOutlined } from '@ant-design/icons';
import { Decoration7 } from '@jiaminghi/data-view-react'
import { useRequest } from 'ahooks';
import { getFetch } from '@/utils/doFetch';
import { mmConversionPx } from '@/utils/transpxmm';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';


const { TabPane } = Tabs;

function PreviewPro({ location }) {
    const [curkey, setcurkey] = useState(0);
    const [current, setcurrent] = useState(1);
    const { data, refresh, loading } = useRequest(() => {
        return getFetch({ url: "/api/template/template_preview", params: location.query })
    })
    const [loadings, setloadings] = useState(false);

    return (
        <div id='diytabes'>
            <Spin size="large" spinning={loading}>
                <Tabs
                    tabBarExtraContent={{
                        left: <div className='center' style={{ marginRight: 12 }}>
                            <div className={styles.back} onClick={() => {
                                history.go(-1)
                            }}>
                                <ArrowLeftOutlined style={{ paddingRight: 6 }} /> 返回
                            </div>

                        </div>,
                        right: <div className='spread' style={{ width: 518, justifyContent: "flex-end" }}>
                            <Pagination current={current} onChange={(val) => {
                                setcurrent(val)
                            }} total={data?.data[curkey]?.data?.length ?? 0} pageSize={1} size='small' showTotal={(s) => `共${s}个模板`} showQuickJumper={false} showSizeChanger={false} />

                            <Button loading={loadings} type='primary' icon={<UploadOutlined />} style={{ marginLeft: 12, height: "64px", borderRadius: 0 }} onClick={async () => {
                             Modal.info({
                                    title: "命名规则",
                                    maskClosable: true,
                                    width: 606,
                                    content: <div>
                                        <InitForm
                                            style={{ marginBottom: -20 }}
                                            submitting={loadings}
                                            fields={{
                                                "variable": {
                                                    "value": null,
                                                    "type": "checktable",
                                                    "title": "",
                                                    "name": [
                                                        "variable"
                                                    ],
                                                    "required": false,
                                                    "columns": [
                                                        {
                                                            "title": "变量名称",
                                                            "dataIndex": "variable_name",
                                                            "key": "variable_name",
                                                        },
                                                        {
                                                            "title": "变量类型",
                                                            "dataIndex": "variable_type",
                                                            "key": "variable_type",
                                                            "search": false
                                                        },
                                                        {
                                                            "title": "数据来源",
                                                            "dataIndex": "source",
                                                            "key": "source",
                                                            "search": false
                                                        }
                                                    ],
                                                    "editable": false,
                                                    "path": "/api/template/variable_list",
                                                    "extraparams": { id: location?.query?.id },
                                                    "rowKey": "variable_name",
                                                    "rowName": "variable_name",
                                                    "tabletype": "radio",
                                                    "pagination": "false",
                                                    "col": {
                                                        "span": 24
                                                    }
                                                },
                                            }}
                                            submitData={async (vals) => {
                                                setloadings(true);
                                                let selectname = Object.values(vals)[0] ?? null;
                                                await setcurname(selectname);
                                                var zip = new JSZip();
                                                let pdflist = Array.prototype.slice.call(document.getElementsByClassName("pdf"));

                                                await Promise.all(pdflist.map(async (item, index) => {
                                                    let pagelistdom = Array.prototype.slice.call(item.getElementsByClassName("avoid"));
                                                    let title = item.getAttribute("data-set-title");
                                                    let filename = `${title}.pdf`;
                                                    let doc = new jsPDF();
                                                    let imgarr = [];
                                                    await Promise.all(pagelistdom.map(async (it, i) => {
                                                        await html2canvas(it, {
                                                            scale: 1,
                                                            allowTaint: true,
                                                            windowWidth: it.scrollWidth,
                                                            windowHeight: it.scrollHeight
                                                        }).then(canvas => {
                                                            let imgData = canvas.toDataURL('image/jpeg', 1.0);
                                                            let printwidth = canvas.width > 1300 ? 1300 : canvas.width;
                                                            let printheight = canvas.width > 1300 ? (canvas.height / canvas.width) * 1300 : canvas.height;
                                                            imgarr.push({
                                                                imgData,
                                                                printwidth,
                                                                printheight,
                                                                index: i
                                                            })
                                                        })
                                                    }))
                                                    //图片排序
                                                    imgarr.sort((a, b) => {
                                                        return a.index - b.index
                                                    }).map(({
                                                        imgData,
                                                        printwidth,
                                                        printheight,
                                                    }, i) => {
                                                        doc.addPage([printwidth, printheight], printheight > printwidth ? "p" : "l").addImage(imgData, 'JPEG', 0, 0, printwidth, printheight, i, "NONE");
                                                    })

                                                    doc.deletePage(1);
                                                    let blob = doc.output('blob', {
                                                        filename
                                                    })
                                                    zip.file(filename, blob)
                                                }))

                                                let content = await zip.generateAsync({
                                                    type: "blob", 
                                                    compressionOptions: {
                                                        level: 9
                                                    }
                                                });
                                                saveAs(content, "pdf.zip");
                                                setloadings(false)
                                                Modal.destroyAll();

                                            }}
                                        >
                                        </InitForm>
                                    </div>,
                                    okText: "确定",
                                    okButtonProps: {
                                        type: "text",
                                        style: { display: "none" }
                                    },
                                })

                            }}>
                                导出PDF
                            </Button>
                        </div>
                    }}>
                    {
                        data?.data ? data?.data?.map?.((it, i) => {
                            let filenamelist = it?.file_name.split(".");//取文件名多个. 
                            let curconfig = it.data[current - 1];
                            return <TabPane tab={filenamelist.filter((item, index) => index < filenamelist.length - 1).join(".")} key={i}>
                                <div style={{ backgroundColor: "#f0f0f0", minHeight: 88 }} id='sees'></div>
                                <div className='center' style={{ backgroundColor: "#f0f0f0", width: "100%", minHeight: "calc(100vh - 88px)", flexDirection: "column" }}>
                                    {
                                        curconfig?.pages && curconfig?.pages.map((it, index) => {
                                            const { backgroundColor, width, height, components, unit } = it;
                                            let realw, realh, zoom = 1;
                                            if (unit == "mm") {
                                                realw = mmConversionPx(width);
                                                realh = mmConversionPx(height);
                                            } else {
                                                realw = width;
                                                realh = height;
                                            }
                                            //预览最大宽度1300
                                            if (realw > 1300) {
                                                zoom = 1300 / realw;
                                                realh = (realh / realw) * 1300
                                                realw = 1300;
                                            }

                                            return <div key={index} style={{ width: realw, height: realh + 68, position: "relative" }}>
                                                <div style={{ backgroundColor, width: realw, height: realh, position: "relative", overflow: "hidden" }} key={it.id}>
                                                    <div style={{ transform: `translateZ(0) scale(${zoom})`, transformOrigin: "left top" }}>
                                                        {
                                                            components.map((item, i) => {
                                                                return React.createElement(Doms[item.type], { ...item, key: i });
                                                            })
                                                        }
                                                    </div>
                                                </div>
                                                <div className={`${styles.pagebadage}`}>
                                                    <Decoration7 style={{ width: '150px', height: '30px' }}>
                                                        <div style={{ padding: "0 12px" }}>
                                                            第{index + 1}页
                                                        </div>
                                                    </Decoration7>

                                                </div>
                                            </div>
                                        })
                                    }
                                </div>

                            </TabPane>
                        }) :
                            <Empty description="没有模板" />
                    }

                </Tabs>
            </Spin>

            <div>
                {
                    data?.data ? data?.data?.map?.((item) => {
                        return item?.data ? item?.data?.map((its, i) => {
                            return <div
                                className='pdf'
                                key={i}
                                style={{
                                    backgroundColor: "#f0f0f0",
                                    width: "100%",
                                    flexDirection: "column",
                                    display: "flex",
                                    justifyContent: "center",
                                    alignItems: "center"
                                }}>
                                {
                                    its?.pages && its?.pages.map((it, index) => {
                                        const { backgroundColor, width, height, components, unit } = it;
                                        let realw, realh, zoom = 1;
                                        if (unit == "mm") {
                                            realw = mmConversionPx(width);
                                            realh = mmConversionPx(height);
                                        } else {
                                            realw = width;
                                            realh = height;
                                        }
                                        //预览最大宽度1300
                                        if (realw > 1300) {
                                            zoom = 1300 / realw;
                                            realh = (realh / realw) * 1300
                                            realw = 1300;
                                        }

                                        return <div className='avoid' key={index} style={{ width: realw, height: realh + 68, position: "relative" }}>
                                            <div style={{ backgroundColor, width: realw, height: realh, position: "relative", overflow: "hidden" }} key={it.id}>
                                                <div style={{ transform: `translateZ(0) scale(${zoom})`, transformOrigin: "left top" }}>
                                                    {
                                                        components.map((item, i) => {
                                                            return React.createElement(Doms[item.type], { ...item, key: i });
                                                        })
                                                    }
                                                </div>
                                            </div>
                                            <div className={`${styles.pagebadage}`}>
                                                <Decoration7 style={{ width: '150px', height: '30px' }}>
                                                    <div style={{ padding: "0 12px" }}>
                                                        第{index + 1}页
                                                    </div>
                                                </Decoration7>

                                            </div>
                                        </div>
                                    })
                                }
                            </div>


                        }) : null
                    }) :
                        <Empty description="没有模板" />
                }



            </div>

        </div>
    );
}

export default PreviewPro;

